package dataStruct.queue.ex3;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Queue;

/**
 * Created by thinkpad on 2016/9/15.
 */
public class Scheduler implements Runnable {
    private Queue<MsgBody> msgQueue;
    private MsgTable msgTable;

    public Scheduler(Queue<MsgBody> msgQueue, MsgTable msgTable, HashMap<Long, ThreadMsgInfo> threadMsgInfoHashMap) {
        this.msgQueue = msgQueue;
        this.msgTable = msgTable;
        this.threadMsgInfoHashMap = threadMsgInfoHashMap;
    }

    private HashMap<Long, ThreadMsgInfo> threadMsgInfoHashMap;
    public Scheduler(Queue<MsgBody> msgQueue, MsgTable msgTable) {
        this.msgQueue = msgQueue;
        this.msgTable = msgTable;
    }

    @Override
    public void run() {
        while(true) {
//            System.out.println("Scheduler---" + Thread.currentThread() + "---msgQueue.size():" + msgQueue.size());
            while (!msgQueue.isEmpty()) {
//                System.out.println("Scheduler---"+ Thread.currentThread()+"---msgQueue.size():"+msgQueue.size());
                MsgBody msgBody = msgQueue.poll();
                msgTable.replaceState(msgBody.getUuid(), State.DONE);
                delay(10000,1000);
//            msgTable.replaceState(msgBody.getUuid(), State.BUSY);
//            if(msgBody.getName().equals("yc")) {
//                delay(100,1000);
//            }
//                System.out.println("Scheduler---" + msgBody.getName() + "-----" + msgBody.getBody() + " " + Thread.currentThread());
//                System.out.println(msgBody.getName() + "-----" + msgBody.getBody() + " " + Thread.currentThread());
                if (msgBody != null) {
                    threadMsgInfoHashMap.put(new Long(Thread.currentThread().getId()), new ThreadMsgInfo(msgBody, State.BUSY));
                    Calendar c = Calendar.getInstance();
                    System.out.println("当前时间毫秒数：" + c.getTimeInMillis()+"---"+msgBody.getName() + "-----" + msgBody.getBody() + " " + Thread.currentThread());
                    threadMsgInfoHashMap.put(new Long(Thread.currentThread().getId()), new ThreadMsgInfo(msgBody, State.IDLE));
                }
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

//            if(msgBody.getName().equals("sun")) {
//                delay(1,10);
//            }
//            msgTable.replaceState(msgBody.getUuid(), State.IDLE);

            }
        }
    }

    void delay(int outCount, int inCount) {
        for(int i = 0; i < outCount;i++){
            for(int j = 0; j < outCount;j++){
            }
        }
    }
}
